import { useAppDispatch } from '@/store';
import { updateHistory } from '@/store/actions/chat';

const askChatGPT = async (id: string, content: string) => {
  // const dispatch = useAppDispatch();
  let returnText = '';

  const response = await fetch('https://open.bigmodel.cn/api/paas/v4/chat/completions', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      Authorization: `Bearer 6bed0d89b36ebca95828f2309547e698.9Lo2velanwxXWg9j`,
    },
    body: JSON.stringify({
      model: 'glm-4',
      stream: true,
      messages: [
        {
          role: 'user',
          content: content,
        },
      ],
    }),
  });
  if (response.ok) {
    if (!response.body) return;
    const reader = response.body.getReader();
    const stream = new ReadableStream({
      async start(controller) {
        function fetchData() {
          reader.read().then(({ done, value }) => {
            if (done) {
              controller.close();
              return;
            }
            const chunkText = new TextDecoder().decode(value);
            chunkText.split('\n').forEach((line) => {
              if (line) {
                if (line === 'data: [DONE]') {
                  return;
                }
                line = line.replaceAll('data: ', '');
                const data = JSON.parse(line);
                if (data.choices[0].finish_reason && data.choices[0].finish_reason === 'stop') {
                  return;
                }
                if (data.choices[0].delta.content) {
                  const text = data.choices[0].delta.content;
                  returnText = returnText + text;
                  // dispatch(updateHistory(id, returnText));
                }
              }
            });
            fetchData();
          });
        }
        fetchData();
      },
    });
    await new Response(stream).text();
  } else {
    return 'Error: ' + response.status;
  }
};

export default askChatGPT;
